<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
    >
          <el-form-item label="报销员工" prop="userId">
            <UserSelect
            class="!w-240px"
              v-model="queryParams.userId"
              @node-change="handleUserSelect"
            />
          </el-form-item>
          <el-form-item label="单据编号" prop="billNo">
            <el-input
                v-model="queryParams.billNo"
                placeholder="请输入单据编号"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
            />
          </el-form-item>
              <el-form-item label="报销日期" prop="billDate">
                <el-date-picker
                    v-model="queryParams.billDate"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="!w-220px"
                />
              </el-form-item>
          <el-form-item label="费用类型" prop="expenseType">
            <el-select
                v-model="queryParams.expenseType"
                placeholder="请选择费用类型"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.OA_EXPENSE_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审批结果" prop="status">
            <el-select
                v-model="queryParams.status"
                placeholder="请选择审批结果"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button 
          v-hasPermi="['oa:expense:export']" 
          :loading="exportLoading" 
          plain 
          type="success" 
          @click="handleExport"
        >
          <Icon class="mr-5px" icon="ep:download" />
          导出
        </el-button>
        <!-- <el-button plain type="primary" @click="handleCreate()">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button> -->
            </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
    <el-table-column label="报销编号" align="center" prop="billNo" min-width="220" />
    <el-table-column label="报销人" align="center" prop="userName" min-width="100" />
    <el-table-column label="费用归属部门" align="center" prop="deptName" min-width="110" />
    <el-table-column label="报销公司" align="center" prop="subjectName" min-width="220" />
    <el-table-column label="费用类型" align="center" prop="expenseType" min-width="80">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.OA_EXPENSE_TYPE" :value="scope.row.expenseType" />
      </template>
    </el-table-column>
    <el-table-column label="费用名称" align="center" prop="expenseName" min-width="100">
      <template #default="scope">
        <dict-tag :type="scope.row.expenseType" :value="scope.row.expenseName" />
      </template>
    </el-table-column>
    <el-table-column label="费用发生日期" align="center" prop="billDate" :formatter="dateFormatter2" min-width="110" />
    <el-table-column label="报销金额" align="center" prop="expenseAmount" min-width="80" />
    <el-table-column label="有无发票" align="center" prop="hasInvoice" min-width="90">
      <template #default="scope">
        <el-tag :type="scope.row.hasInvoice === 1 ? 'success' : 'danger'">{{ scope.row.hasInvoice === 1 ? '有' : '无' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="审批结果" align="center" prop="status" min-width="100">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="scope.row.status" />
      </template>
    </el-table-column>
    <!-- <el-table-column label="单据编号" align="center" prop="billNo" width="140" /> -->
    
    <el-table-column label="支付状态" align="center" prop="payStatus" min-width="120">
      <template #default="scope">
        <div class="flex items-center justify-center gap-2">
          <span v-if="scope.row.payStatus === 1">已支付</span>
          <span v-else-if="scope.row.payStatus === 2">已取消</span>
          <span v-else>未支付</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="付款日期" align="center" prop="payDate" :formatter="dateFormatter2" min-width="110" />
    
    <!-- <el-table-column label="付款金额" align="center" prop="invoiceAmount" width="80" /> -->
    
    
    <el-table-column label="付款人" align="center" prop="payerName" min-width="100" />
    <!-- <el-table-column label="创建者" align="center" prop="creatorName" min-width="100" /> -->
    <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" min-width="180" />
    <el-table-column label="操作" align="center" min-width="180" fixed="right">
      <template #default="scope">
        <el-button
            v-hasPermi="['oa:expense:query']"
            link
            type="primary"
            @click="handleDetail(scope.row)"
        >
          详情
        </el-button>

        <!-- <el-button
            v-hasPermi="['oa:expense:query']"
            link
            type="primary"
            @click="handleProcessDetail(scope.row)"
        >
          进度
        </el-button> -->
        
      </template>
    </el-table-column>
  </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

  <DetailDrawer
    v-model="showDetailDrawer"
    :task-id="currentExpenseId"
    title="报销详情" />



  <ProcessInstanceDetailDrawer
    v-model="showDrawer" :process-instance-id="currentProcessInstanceId" title="流程进度"
    @success="handleDrawerSuccess" />


</template>
<script lang="ts" setup>
  import { DICT_TYPE, getIntDictOptions,getStrDictOptions } from '@/utils/dict'
  import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
  import { ExpenseApi, ExpenseVO } from '@/api/oa/expense'
  import * as ProcessInstanceApi from '@/api/bpm/processInstance'
  import UserSelect from '@/views/system/user/UserSelect.vue'
  import DetailDrawer from '@/views/oa/expense/components/DetailDrawer.vue'
  import ProcessInstanceDetailDrawer from '@/views/bpm/processInstance/components/ProcessInstanceDetailDrawer.vue'
  import download from '@/utils/download'
  defineOptions({ name: 'ExpenseOut' })

  const message = useMessage() // 消息弹窗
  const router = useRouter() // 路由
  const { t } = useI18n() // 国际化


  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const list = ref([]) // 列表的数据
  const queryParams = reactive({
      pageNo: 1,
    pageSize: 10,
    userId: undefined,
    billNo: undefined,
    billDate: [],
    expenseType: undefined,
    status: undefined,
    payStatus: 1,
  })
  const queryFormRef = ref() // 搜索的表单

  const showDetailDrawer = ref(false)
  const currentExpenseId = ref<number | undefined>(undefined)

  const showFinishDialog = ref(false)
  const showDrawer = ref(false)
  const currentProcessInstanceId = ref('')

  const exportLoading = ref(false) // 导出的加载中


  /** 查询列表 */
  const getList = async () => {
    loading.value = true
    try {
              const data = await ExpenseApi.getExpensePage(queryParams)
      list.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  /** 添加操作 */
  const handleCreate = () => {
    router.push({ name: 'ExpenseCreate' })
  }

  /** 详情操作 */
  const handleDetail = (row: ExpenseVO) => {
    currentExpenseId.value = Number(row.id)
    showDetailDrawer.value = true
  }

  /** 取消请假操作 */
  const cancelProcess = async (row) => {
    // 二次确认
    const { value } = await ElMessageBox.prompt('请输入取消原因', '取消流程', {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
      inputErrorMessage: '取消原因不能为空'
    })
    // 发起取消
    await ProcessInstanceApi.cancelProcessInstanceByStartUser(row.id, value)
    message.success('取消成功')
    // 刷新列表
    await getList()
  }
  /** 审批进度 */
  const handleProcessDetail = (row) => {
    currentProcessInstanceId.value = row.processInstanceId
    showDrawer.value = true
  }



  const handleUserSelect = (val) =>{
    queryParams.userId = val ? val.id : undefined
    console.log('queryParams.userId',queryParams.userId)
  }


  const handleDrawerSuccess = () => {
    showDrawer.value = false
    getList()
  }

  /** 导出按钮操作 */
  const handleExport = async () => {
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await ExpenseApi.exportExpense(queryParams)
      download.excel(data, '报销支出.xls')
    } catch {
    } finally {
      exportLoading.value = false
    }
  }

  /** 编辑操作 */
  const handleEdit = (row: ExpenseVO) => {
    router.push({
      name: 'ExpenseEdit',
      query: {
        id: row.id,
        processInstanceId: row.processInstanceId
      }
    })
  }

  const onFinishDialogConfirm = (data) => {
    // 处理确认逻辑
    showFinishDialog.value = false
    // 例如刷新列表
    getList()
  }

  // fix: 列表不刷新的问题。
  watch(
      () => router.currentRoute.value,
      () => {
        getList()
      }
  )

  /** 初始化 **/
  onMounted(() => {
    getList()
  })
</script>
